package entityData

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-next-entity/nextEntity"
	"strings"
)

type source struct {
}

func (e *source) QueryCount(tableName string) (int, error) {
	sql := "SELECT COUNT(1) FROM " + tableName
	return commSql.QueryCount(sql)
}

func (e *source) QueryPageList(tableName string, pageNum, pageSize int) ([]*nextEntity.SourceEntity, error) {
	result := make([]*nextEntity.SourceEntity, 0)

	mtsql := "SELECT s1.* FROM " + tableName + " s1 ORDER BY s1.ID"
	sql := commSql.SqlBuilder.BuildSelectPage(tableName, nil, nil, mtsql, pageNum, pageSize)
	list, err := commSql.Query(nextEntity.Type.SourceEntity.Type(), sql)
	if err != nil {
		return result, err
	}

	for _, v := range list {
		result = append(result, v.(*nextEntity.SourceEntity))
	}

	return result, nil
}

func (e *source) QueryEntityByKey(tableName, key string) (*nextEntity.SourceEntity, error) {
	sql := "SELECT * FROM " + tableName + "  WHERE 'key' = '" + key + "'"
	list, err := commSql.Query(nextEntity.Type.SourceEntity.Type(), sql)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return nil, nil
	}

	return list[0].(*nextEntity.SourceEntity), nil
}

func (e *source) QueryEntityByKeys(tableName string, keys []string) (map[string]*nextEntity.SourceEntity, error) {
	result := make(map[string]*nextEntity.SourceEntity)

	// 构造SQL语句和参数列表
	args := make([]interface{}, 0)
	sb := strings.Builder{}
	sb.WriteString("SELECT * FROM " + tableName + " s1 WHERE s1.key in (")
	for idx, key := range keys {
		args = append(args, key)

		sb.WriteString("?")
		if idx < len(keys)-1 {
			sb.WriteString(",")
		} else {
			sb.WriteString(")")
		}
	}
	sql := sb.String()

	list, err := commSql.SQuery(nextEntity.Type.SourceEntity.Type(), sql, args)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return result, nil
	}

	for _, v := range list {
		entity := v.(*nextEntity.SourceEntity)
		result[entity.Key] = entity
	}

	return result, nil
}

func (e *source) SaveEntity(tableName, key string, value map[string]interface{}) error {
	exist, err := e.QueryEntityByKey(tableName, key)
	if err != nil {
		return err
	}

	if exist == nil {
		entity := nextEntity.Type.SourceEntity.NewEntity().(*nextEntity.SourceEntity)
		entity.Key = key
		entity.Value = value
		return commSql.InsertRecord(tableName, entity)
	} else {
		exist.Value = value
		return commSql.UpdateRecordById(tableName, exist)
	}
}

func (e *source) InsertEntity(tableName, key string, value map[string]interface{}) error {
	entity := nextEntity.Type.SourceEntity.NewEntity().(*nextEntity.SourceEntity)
	entity.Key = key
	entity.Value = value
	return commSql.InsertRecord(tableName, entity)
}
